class Solution {
public:
    void reverse(string &s, int i, int j) {
        while (i < j) {
            swap(s[i], s[j]);
            i++, j--;
        }
    }

    string reverseWords(string s) {
        int slow = 0, fast = 0;
        for (; fast < s.size(); fast++) {
            if (s[fast] == ' ' && slow == 0) continue;
            if (s[fast] != ' ') s[slow++] = s[fast];
            else if (s[fast] == ' ' && s[slow - 1] != ' ') {
                s[slow++] = s[fast];
            }
        }
        if (slow > 0 && s[slow - 1] == ' ') slow--;
        s = s.substr(0, slow);
        reverse(s, 0, s.size() - 1); 
        int i, j;
        for (i = 0, j = 0; j < s.size(); j++) {
            if (s[j] != ' ') continue;
            reverse(s, i, j - 1);
            i = j + 1;
        }
        reverse(s, i, j - 1);
        return s;
    }
};
